package com.jl.card.gp;

import com.jl.card.JL;
import com.jl.util.HexUtil;
/**
 * not test
 * @author Administrator
 */
public class SCP01 extends SCP{

	private byte[] bENCSession = new byte[24];
	private byte[] bMACSession = new byte[24];
	private byte[] bDEKSession = new byte[24];
	private byte[] ICV = new byte[8];

	public SCP01() {
		super();
		protocol = SCP_01;
	}

	@Override
	public void generateSessionKeys() {
		byte[] bDerivation = new byte[16];
		byte[] bTmp = null;
		System.arraycopy(cardRand, 4, bDerivation, 0, 4);
		System.arraycopy(hostRand, 0, bDerivation, 4, 4);
		System.arraycopy(cardRand, 0, bDerivation, 8, 4);
		System.arraycopy(hostRand, 4, bDerivation, 12, 4);

		bTmp = Util.tripleDESECB(gpKey.getENC(), bDerivation, false);
		System.arraycopy(bTmp, 0, bENCSession, 0, 16);
		System.arraycopy(bTmp, 0, bENCSession, 16, 8);

		bTmp = Util.tripleDESECB(gpKey.getMAC(), bDerivation, false);
		System.arraycopy(bTmp, 0, bMACSession, 0, 16);
		System.arraycopy(bTmp, 0, bMACSession, 16, 8);
		bDEKSession = gpKey.getDEK();
	}

	@Override
	public byte[] wrap(byte[] cmd) {
		byte[] bTmp = null;
		int len = 0;
		int il = 0;
		if (cmd[0] == (byte) 0x84 && cmd[1] == (byte) 0x82) {

		} else if (level == JL.GP_AUTH_LEVEL_MAC
				|| level == JL.GP_AUTH_LEVEL_ENC_MAC) {
			cmd[0] |= 0x04;
		} else if (level == JL.GP_AUTH_LEVEL_NO) {
			return cmd;
		}
		len = cmd.length;
		if (len > 250)
			return null;
		if (len == 5)
			cmd[4] = (byte) 0;
		if (len == 4) {
			len = 5;
			byte[] temp = new byte[5];
			System.arraycopy(cmd, 0, temp, 0, 4);
			cmd = temp;
		}
		cmd[4] = (byte) ((cmd[4] & 0xFF) + 8);
		ICV = Util.tripleDES_MAC(bMACSession, cmd, ICV);
		cmd = HexUtil.contacByteArray(cmd, ICV);
		if (level == (byte) 0x83) {
			len = cmd.length - 4 - 8;
			il = (len + 8) & 0xF8;
			bTmp = new byte[il];
			bTmp[0] = (byte) (len - 1);
			bTmp[len] = (byte) 0x80;
			System.arraycopy(cmd, 5, bTmp, 1, len - 1);
			bTmp = Util.tripleDESECB(bENCSession, bTmp, false);
			byte[] bTmp1 = new byte[5 + bTmp.length + 8];
			System.arraycopy(cmd, 0, bTmp1, 0, 4);
			System.arraycopy(bTmp, 0, bTmp1, 5, bTmp.length);
			System.arraycopy(cmd, cmd.length - 8, bTmp1, bTmp1.length - 8, 8);
			cmd = bTmp1;
			cmd[4] = (byte) (cmd.length - 5);
		}
		return cmd;
	}

	@Override
	public byte[] unwrap(byte[] res) {
		return res;
	}
}